const log4js = require("log4js");
const fs = require("fs-extra");
const zlib = require("zlib");


const ML = NCUTCAT.localProperty.debug_msg_max_length;
const ML2 = ML / 2;
const DEBUG = NCUTCAT.localProperty.debug;


const LOG_FILE_PATH = "logs/current.log";

if (!fs.existsSync("logs/")) fs.mkdirSync("logs");
// 启动时自动储存上次日志文件
if (fs.existsSync(LOG_FILE_PATH)) {
    const date = fs.statSync(LOG_FILE_PATH).mtime;
    // const date = new Date();
    const logFilename = `logs/${date.getFullYear()}-${date.getMonth() + 1}-${date.getDay()}_${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}.log`;
    fs.renameSync(LOG_FILE_PATH, logFilename);
    setTimeout(() => {
        //压缩上一次的
        let gzip = zlib.createGzip();
        let rs = fs.createReadStream(logFilename);
        let ws = fs.createWriteStream(logFilename + ".gz");
        rs.pipe(gzip).pipe(ws);
        fs.unlinkSync(logFilename);
    }, 1);
}

log4js.configure({
    appenders: {
        out: {
            type: "stdout",
            layout: {
                type: "pattern",
                pattern: "[%d{MM/dd hh:mm:ss}] [%[%p%]] %m"
            }
        },
        app: {
            type: "file",
            filename: LOG_FILE_PATH,
            layout: {
                type: "pattern",
                pattern: "%d %p %m"
            }
        }
    },
    categories: {
        default: {
            appenders: ["out", "app"],
            level: "info"
        }
    }
});

const logger = log4js.getLogger("default");

// 多参数输出，但仅限于输出 INFO 级别
NCUTCAT.log = function(...p) {
    let msg = "";
    for (const v of p) {
        if (v) msg += v + " ";
    }
    logger.info(msg);
};

// INFO 级别输出
NCUTCAT.infoLog = (info = "", value = "") => {
    let msg = value;
    if (info.toUpperCase() != "INFO") {
        msg = [info, "-", value].join(" ");
    }
    logger.info(msg);
};

// INFO 级别输出
NCUTCAT.info = (...p) => {
    let msg = "";
    for (const v of p) {
        if (v) msg += v + " ";
    }
    logger.info(msg);
};

// ERROR 级别输出
NCUTCAT.error = (msg, err) => {
    logger.error(msg);
    if (err) logger.error(err);
};

// WARN 级别输出
NCUTCAT.warning = (title, msg = null) => {
    logger.warn(title);
    if (msg) logger.warn(msg);
};

if (DEBUG)
    NCUTCAT.debug = (title, msg) => {
        if (typeof msg === 'object') msg = JSON.stringify(msg);
        let l = msg.length;
        NCUTCAT.infoLog(title + ' - ' + ("DEBUG".rainbow),
            (l <= ML ? msg : (msg.substring(0, ML2) + '...' + msg.substring(l - ML2, l)))
        );
    }
else NCUTCAT.debug = () => undefined;